package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.GrammarInfo
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import kotlinx.android.synthetic.main.fragment_words_cognition.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException

/**
 * @author : Admin
 * @date   : 2020/12/7
 * @desc   :
 */
class GrammarCognitionFragment : BaseFragment(), OnChartValueSelectedListener {
    private val pieEntries = mutableListOf<PieEntry>()
    private val colors = mutableListOf<Int>()
    private val zsdArea by lazy { arguments?.getString("zsdarea") }
    private lateinit var viewModel: PaperViewModel
    override fun createLayout(): Int {
        return R.layout.fragment_words_cognition
    }

    override fun initView(view: View?) {
        viewModel = ViewModelProvider(requireActivity()).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        button.text = "语法掌握率历史变化轨迹→"
        button.setOnClickListener {
            startActivity(Intent(requireContext(), GrammarTrailActivity::class.java).apply {
                putExtra("zsd", zsdArea)
                putExtra("stuID",viewModel.StuID.value)
            })
        }
        getStuGrammar()
    }

    @SuppressLint("CheckResult")
    private fun getStuGrammar() {
        val method = BkApiMethods(requireContext())
        val params = BkApiMethods.Paramas()
        params["ZsdArea"] = zsdArea
        params["StuID"] = viewModel.StuID.value
        method.getStuGrammar(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                if (it.Data.AllNum == 0) {
                    group.visibility = View.GONE
                    tv_empty.visibility = View.VISIBLE
                } else {
                    group.visibility = View.VISIBLE
                    tv_empty.visibility = View.GONE
                    initGrammarInfo(it.Data)
                    initPieChart(it.Data)
                }
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                getString(R.string.aibk_network_timeout)
            } else {
                getString(R.string.aibk_server_sick)
            }
            MyToast.showToast(error)
        })
    }

    @SuppressLint("SetTextI18n")
    private fun initGrammarInfo(data: GrammarInfo) {
        when (data.Conclusion) {
            0 -> {
                tv_extra.visibility = View.GONE
                tv_percent.visibility = View.GONE
                iv_icon.setImageResource(R.mipmap.aibk_icon_grammar_no)
                tv_vocabinfo_child.visibility = View.GONE
                tv_vocabinfo_sub.visibility = View.GONE
                val graspGrammar = data.GraspNum.toString()
                val unGraspGrammar = data.UnGraspNum.toString()
                val unAssessGrammar = data.UnAssessNum.toString()
                tv_vocabinfo.visibility = View.VISIBLE
                tv_vocabinfo.text = HtmlUtils.setText(
                    "熟练掌握语法${graspGrammar}个，薄弱语法${unGraspGrammar}个；（尚有${unAssessGrammar}个语法未采集到学习数据）")
                val strInfo = tv_vocabinfo.text
                val indexGraspGrammar = strInfo.indexOf(graspGrammar)
                val spanStr = SpannableString(strInfo)
                addClickSpan(spanStr, "#22d7bb", indexGraspGrammar,
                        indexGraspGrammar + graspGrammar.length, 0, data.GraspNum)
                addClickSpan(spanStr, "#ffd234", indexGraspGrammar + graspGrammar.length + 6,
                        indexGraspGrammar + graspGrammar.length + 6 + unGraspGrammar.length, 1, data.UnGraspNum)
                addClickSpan(spanStr, "#e1e1e1",
                    indexGraspGrammar + graspGrammar.length + 11 + unGraspGrammar.length,
                    indexGraspGrammar + graspGrammar.length + 11 + unGraspGrammar.length +
                            unAssessGrammar.length,
                        2, data.UnAssessNum)
                tv_vocabinfo.text = spanStr
                tv_vocabinfo.movementMethod = LinkMovementMethod.getInstance()
            }
            else -> {
                tv_extra.visibility = View.VISIBLE
                tv_percent.visibility = View.VISIBLE
                tv_extra.text = "${Ext.TESTNAME}必考语法掌握率"
                tv_percent.text = HtmlUtils.setText(getString(R.string.words_percent,
                    BigDecimal(data.GraspNum * 100.toDouble() / data.AllNum.toDouble()).setScale(1,
                        BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString()))
                when (data.Conclusion) {
                    1 -> {
                        iv_icon.setImageResource(R.mipmap.aibk_icon_grammar_c)
                        tv_vocabinfo_child.visibility = View.VISIBLE
                        tv_vocabinfo_child.text = "语法知识薄弱"
                        tv_vocabinfo_child.setTextColor(Color.parseColor("#ffd234"))
                        tv_vocabinfo_sub.visibility = View.VISIBLE
                        tv_vocabinfo_sub.text = HtmlUtils.setText("${Ext.TESTNAME}常考的<b>${
                            if (data.GraspStateList.size > 1) data.GraspStateList[0] + "、" + data.GraspStateList[1] else data.GraspStateList[0]
                        }</b>等<font color='#ffd234'>${data.GraspStateNum}</font>个专题掌握较差~要努力噢！")
                        tv_vocabinfo.visibility = View.GONE
                    }
                    2 -> {
                        iv_icon.setImageResource(R.mipmap.aibk_icon_grammar_b)
                        tv_vocabinfo_child.visibility = View.VISIBLE
                        tv_vocabinfo_child.text = "语法知识一般"
                        tv_vocabinfo_child.setTextColor(Color.parseColor("#22d7bb"))
                        tv_vocabinfo_sub.visibility = View.VISIBLE
                        tv_vocabinfo_sub.text = HtmlUtils.setText("${Ext.TESTNAME}常考的<b>${
                            if (data.GraspStateList.size > 1) data.GraspStateList[0] + "、" + data.GraspStateList[1] else data.GraspStateList[0]
                        }</b>等<font color='#22d7bb'>${data.GraspStateNum}</font>个专题需巩固~要加油噢！")
                        tv_vocabinfo.visibility = View.GONE
                    }
                    3 -> {
                        iv_icon.setImageResource(R.mipmap.aibk_icon_grammar_a)
                        tv_vocabinfo_child.visibility = View.VISIBLE
                        tv_vocabinfo_child.text = "语法知识较好"
                        tv_vocabinfo_child.setTextColor(Color.parseColor("#2dbcff"))
                        tv_vocabinfo_sub.visibility = View.VISIBLE
                        tv_vocabinfo_sub.text = HtmlUtils.setText("${Ext.TESTNAME}常考的<b>${
                            if (data.GraspStateList.size > 1) data.GraspStateList[0] + "、" + data.GraspStateList[1] else data.GraspStateList[0]
                        }</b>等<font color='#2dbcff'>${data.GraspStateNum}</font>个专题掌握较好~继续保持！")
                        tv_vocabinfo.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun addClickSpan(str: SpannableString, color: String, start: Int, end: Int, type: Int, num: Int) {
        str.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                if (num == 0) {
                    return
                }
                val intent = Intent().apply {
                    putExtra("type", type)
                    putExtra("zsd", zsdArea)
                    putExtra("stuID",viewModel.StuID.value)
                }
                if (type != 2) {
                    intent.setClass(requireContext(), GrammarListActivity::class.java)
                } else {
                    intent.setClass(requireContext(), UnStudyTopicListActivity::class.java)
                }
                startActivity(intent)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = Color.parseColor(color)
                ds.isUnderlineText = true
            }
        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }

    private fun initPieChart(data: GrammarInfo) {
        if (data.Conclusion == 0) {
            pieEntries.clear()
            val dataMap = mapOf("熟练掌握" to data.GraspNum.toFloat(),
                "薄弱" to data.UnGraspNum.toFloat(), "尚未学习" to data.UnAssessNum.toFloat())
            val sortedMap = dataMap.toList().sortedByDescending { it.second }
            pieEntries.add(PieEntry(sortedMap[1].second, sortedMap[1].first))
            colors.clear()
            colors.add(Color.parseColor(when (sortedMap[1].first) {
                "熟练掌握" -> "#22d7bb"
                "薄弱" -> "#ffd234"
                else -> "#e1e1e1"
            }))
            pieEntries.add(PieEntry(sortedMap[0].second, sortedMap[0].first))
            colors.add(Color.parseColor(when (sortedMap[0].first) {
                "熟练掌握" -> "#22d7bb"
                "薄弱" -> "#ffd234"
                else -> "#e1e1e1"
            }))
            pieEntries.add(PieEntry(sortedMap[2].second, sortedMap[2].first))
            colors.add(Color.parseColor(when (sortedMap[2].first) {
                "熟练掌握" -> "#22d7bb"
                "薄弱" -> "#ffd234"
                else -> "#e1e1e1"
            }))
            val percent = BigDecimal(100) - BigDecimal(
                data.GraspNum.toDouble() *100/ data.AllNum.toDouble()).setScale(0, RoundingMode
                .HALF_UP) - BigDecimal(
                data.UnGraspNum.toDouble() *100/ data.AllNum.toDouble()).setScale(0,
                RoundingMode.HALF_UP)
            val pieManager = PieChartManager(chart_words_cognition, "grammar",
                percent.intValueExact())
            pieManager.showSolidPieChart(pieEntries, colors)
        } else {
            pieEntries.clear()
            pieEntries.add(PieEntry(data.GraspNum.toFloat(), "已掌握" + data.GraspNum))
            colors.clear()
            colors.add(Color.parseColor("#22d7bb"))
            pieEntries.add(
                PieEntry(data.AllNum.toFloat() - data.GraspNum.toFloat(), "语法" + data.AllNum))
            colors.add(Color.parseColor("#2dbcff"))
            val pieManager = PieChartManager(chart_words_cognition, "grammar", 0)
            pieManager.showRingPieChart(pieEntries, colors)
        }
        chart_words_cognition.setOnChartValueSelectedListener(this)
    }


    override fun onValueSelected(e: Entry?, h: Highlight?) {
        val label = (e as PieEntry).label
        val intent = Intent().apply {
            putExtra("zsd", zsdArea)
        }
        when {
            label == "熟练掌握" -> {
                intent.setClass(requireContext(), GrammarListActivity::class.java)
                intent.putExtra("type", 0)
            }
            label == "薄弱" -> {
                intent.setClass(requireContext(), GrammarListActivity::class.java)
                intent.putExtra("type", 1)
            }
            label.contains("已掌握") -> {
                intent.setClass(requireContext(), GrammarListActivity::class.java)
                intent.putExtra("type", 2)
            }
            label == "尚未学习" -> {
                intent.setClass(requireContext(), UnStudyTopicListActivity::class.java)
                intent.putExtra("stuID", viewModel.StuID.value)
            }
            label.contains("语法") -> {
                intent.setClass(requireContext(), GrammarListActivity::class.java)
                intent.putExtra("type", -1)
            }
        }
        startActivity(intent)
    }

    override fun onNothingSelected() {

    }
}